<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">

      <el-form-item label="班级名称" prop="className">
        <el-input v-model="queryParams.className" placeholder="请输入班级名称" clearable size="small" style="width: 180px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学期" prop="termId">
        <el-select v-model="queryParams.termId" placeholder="请选择" style="width:250px">
          <el-option v-for="item1 in termTimeList" :key="item1.id" :label="item1.tetiBeginYear + '~' + item1.tetiEndYear"
            :value="item1.id">
            <span style="float: left">{{ item1.tetiBeginYear + '~' + item1.tetiEndYear }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item1.remarks }}</span>
          </el-option>
        </el-select>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">班级课表录入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-upload2" size="mini" @click="importData">导入班级课表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading">
          导出班级课表
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" ref="curriculumTable" :data="bclassList" highlight-current-row
      @current-change="handleCurrentChange" :stripe="true">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="名称" align="center" prop="id">
        <template slot-scope="scope">
          {{ scope.row.className }} <span style="color:green">【{{ scope.row.remarks }}】</span>课表
        </template>
      </el-table-column>

      <el-table-column label="学期" align="center" prop="remarks" />
      <el-table-column label="班级名称" align="center" prop="className" :show-overflow-tooltip="true" />
      <el-table-column label="班主任" align="center" prop="sysuName" :show-overflow-tooltip="true">

      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <el-button size="mini" circle type="success" icon="el-icon-edit" @click="handleUpdate(scope.row)" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button size="mini" circle type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog title="导入班级课表" :visible.sync="importVisible" width="400px">
      <el-upload v-loading="importLoading" class="upload-demo" drag :action="upload.url" :headers="upload.headers"
        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :file-list="fileList">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip"><el-link type="primary" @click="importTemplateFile">模板下载</el-link></div>
      </el-upload>
    </el-dialog>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学期" prop="termId">
              <el-select v-model="form.termId" placeholder="请选择" style="width:100%">
                <el-option v-for="item1 in termTimeList" :key="item1.id"
                  :label="item1.tetiBeginYear + '~' + item1.tetiEndYear" :value="item1.id + ''">
                  <span style="float: left">{{ item1.tetiBeginYear + '~' + item1.tetiEndYear }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item1.remarks }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="classId">
              <el-select @change="classChange" v-model="form.classId" placeholder="请选择" style="width:100%">
                <el-option v-for="item1 in safeclassList" :key="item1.id" :label="item1.className" :value="item1.id + ''">
                  <span style="float: left">{{ item1.className }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item1.classTeacherId }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">班级课表</el-divider>
        <div  v-if="componentKey">
          <el-table :data="curriculumData" border :stripe="true" class="curriculumTable" v-loading="detailLoading">
            <el-table-column prop="sessionsId" label="节次" width="100" height="50" align="center"> </el-table-column>
            <el-table-column prop="mondaySubjectId" label="星期一" align="center" style="line-height: 26px;">
              <editable-cell :show-input="row.editMode" slot-scope="{row}" :selectDataList="sub"
                :style="row.mondaySubjectId ? getbgcolor(row.mondaySubjectId) : 'color:#606266'"
                v-model="row.mondaySubjectId">
                <span slot="content">{{ getSubjectLabel(row.mondaySubjectId) || '未排课' }}</span>
              </editable-cell>
            </el-table-column>
            <el-table-column label="星期二" align="center">
              <editable-cell :show-input="row.editMode" slot-scope="{row}" :selectDataList="sub"
                :style="row.tuesdaySubjectId ? getbgcolor(row.tuesdaySubjectId) : 'color:#606266'"
                v-model="row.tuesdaySubjectId">
                <span slot="content">{{ getSubjectLabel(row.tuesdaySubjectId) || '未排课' }}</span>
              </editable-cell>
            </el-table-column>
            <el-table-column label="星期三" align="center">
              <editable-cell :show-input="row.editMode" slot-scope="{row}" :selectDataList="sub"
                :style="row.wednesdaySubjectId ? getbgcolor(row.wednesdaySubjectId) : 'color:#606266'"
                v-model="row.wednesdaySubjectId">
                <span slot="content">{{ getSubjectLabel(row.wednesdaySubjectId) || '未排课' }}</span>
              </editable-cell>
            </el-table-column>
            <el-table-column label="星期四" align="center">
              <editable-cell :show-input="row.editMode" slot-scope="{row}" :selectDataList="sub"
                :style="row.thursdaySubjectId ? getbgcolor(row.thursdaySubjectId) : 'color:#606266'"
                v-model="row.thursdaySubjectId">
                <span slot="content">{{ getSubjectLabel(row.thursdaySubjectId) || '未排课' }}</span>
              </editable-cell>
            </el-table-column>
            <el-table-column label="星期五" align="center">
              <editable-cell :show-input="row.editMode" slot-scope="{row}" :selectDataList="sub"
                :style="row.fridaySubjectId ? getbgcolor(row.fridaySubjectId) : 'color:#606266'"
                v-model="row.fridaySubjectId">
                <span slot="content">{{ getSubjectLabel(row.fridaySubjectId) || '未排课' }}</span>
              </editable-cell>
            </el-table-column>
            <el-table-column label="星期六" align="center">
              <editable-cell :show-input="row.editMode" slot-scope="{row}" :selectDataList="sub"
                :style="row.saturdaySubjectId ? getbgcolor(row.saturdaySubjectId) : 'color:#606266'"
                v-model="row.saturdaySubjectId">
                <span slot="content">{{ getSubjectLabel(row.saturdaySubjectId) || '未排课' }}</span>
              </editable-cell>
            </el-table-column>
            <el-table-column label="星期日" align="center">
              <editable-cell :show-input="row.editMode" slot-scope="{row}" :selectDataList="sub"
                :style="row.sundaySubjectId ? getbgcolor(row.sundaySubjectId) : 'color:#606266'"
                v-model="row.sundaySubjectId">
                <span slot="content">{{ getSubjectLabel(row.sundaySubjectId) || '未排课' }}</span>
              </editable-cell>
            </el-table-column>
          </el-table>
        </div>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { findCurriculumPageList, addOrUpdateCurriculum, findDetail, deleteCurriculum, curriculumImportTemplate, exportCurriculum } from "@/api/classManage/classCurriculum";
import { listTermtime } from "@/api/system/termtime.js";
import { findTeacherClassPageList } from "@/api/classManage/classInfo";
import { sessionsList } from "@/api/baseData/sectiontimemanagement";
import EditableCell from "@/views/classManage/classCurriculum/EditableCell";
import { subjectList, subjectListByClass } from "@/api/educational/subject.js";
import { getToken } from '@/utils/auth'


export default {
  name: "BClass",
  components: {
    EditableCell
  },
  data() {
    return {
      exportLoading: false,
      detailLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      rowList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      stuCount: 0,
      // 字典表格数据
      bclassList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 班主任
      userOptions: [],
      // 状态数据字典
      statusOptions: [],
      // 班级所属部门
      classDeptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        className: undefined,
        status: undefined,
        classDept: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        termId: [
          { required: true, message: "请选择班级课表所在学期", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "请选择班级", trigger: "blur" }
        ]
      },
      curriculumData: [],
      termTimeList: [],
      studentLoading: false,
      studentDialogVisible: false,
      safeclassList: [],
      subjList: [],
      subjectStyleList: ["#ff4949", "#46a6ff", "#1682e6", "#1890ff", "#11b95c", "#13ce66", "#ffba00", "#e6a700", "#3fe600", "#3cb6a0", "#3cb3b6",
        "#3c8fb6", "#3c7bb6", "#3c4db6"],
      importVisible: false,
      upload: {
        url: process.env.VUE_APP_BASE_API + '/classInfo/importData',
        headers: { Authorization: "Bearer " + getToken() },
      },
      fileList: [],
      importLoading: false,
      currRow: null,
      sub: [],
      classid: -1,
      componentKey: true,
      mainId: 0
    };
  },
  created() {
    this.getList();
    this.getTermTimeList()
    this.getClassList()
    this.getSessionsList()
    this.getSubjectList()
  },
  methods: {
    classChange() {
      this.classid = this.form.classId;
      this.termId = this.form.termId;
      findDetail({ classId: this.classid,termId: this.termId }).then(resp => {
          this.form = resp.data
          if(this.form.detailList == null){
            this.getSessionsList();
          }else{
            this.curriculumData = resp.data.detailList
          }
        })
      this.getSubjectListByClass();
    },
    handleCurrentChange(currentRow) {
      this.currRow = currentRow
    },
    importTemplateFile() {
      console.log(123)
      curriculumImportTemplate().then(response => {
        console.log(response.data)
        this.fileDownload(response.data, "班级课表导入模板.xlsx");
      });
    },
    importData() {
      //打开导入页面
      this.importVisible = true
      this.fileList = []
    },
    //上传成功后触发
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.$message({ message: '导入成功', type: 'success' });
        this.importLoading = false
        this.importVisible = false
        this.getList()
      } else {
        this.$message.error(res.message);
        this.importLoading = false
      }
      this.fileList = []

    },
    //上传图片前触发
    beforeAvatarUpload(file) {
      this.importLoading = true
      console.log(file.name.lastIndexOf('.xlsx'))
      if (file.name.lastIndexOf('.xlsx') < 0 && file.name.lastIndexOf('.XLSX') < 0) {
        this.$message({
          message: '上传文件只能是.xlsx文件',
          type: 'warning'
        });
        return false
      }
      console.log(file, 'beforefile')
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.currRow == null) {
        this.$message({ message: '请选择一行数据进行导出', type: 'warning' });
        return
      }
      this.exportLoading = true
      exportCurriculum({ id: this.currRow.id }).then(response => {
        this.fileDownload(response.data, "学生联系人.xlsx");
        this.exportLoading = false
        this.currRow = null
        this.$refs.curriculumTable.setCurrentRow(null);
      }).catch(function () {
        this.exportLoading = false
        this.currRow = null
        this.$refs.curriculumTable.setCurrentRow(null);
      })
    },
    //选择颜色
    getbgcolor(subjId) {
      let color = ""
      this.subjList.forEach((item, index) => {
        if (item.id == subjId) {
          if ((index + 1) > this.subjectStyleList.length) {
            color = this.subjectStyleList[(index + 1) % this.subjectStyleList.length]
          } else {
            color = this.subjectStyleList[index]
          }
        }
      })
      return 'background: ' + color + ';color:#FFF'
    },
    //获取科目名称
    getSubjectLabel(val) {
      let name = "未排课"
      console.log("value:",val);
      this.subjList.forEach(item => {
        if (item.id == val) {
          name = item.subjName
        }
      })
      return name
    },
    //查询科目
    getSubjectList() {
      subjectList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.subjList = response.data.list;
        this.subjList.forEach((item, index) => {

        })
      }
      );
    },
    getSubjectListByClass() {
      subjectListByClass(this.classid).then(response => {
        this.subjList = response.data;
        this.sub = response.data;
      });
    },
    cellClickFun(row, column, cell, event) {
      console.log(row, column, cell, event)
    },
    getSessionsList() {
      this.curriculumData = []
      sessionsList({ pageSize: 20, pageNum: 1 }).then(resp => {
        resp.data.list.forEach(item => {
          this.curriculumData.push({
            sessionsId: item.coseCode,
            mondaySubjectId: null,
            tuesdaySubjectId: null,
            wednesdaySubjectId: null,
            thursdaySubjectId: null,
            fridaySubjectId: null,
            saturdaySubjectId: null,
            sundaySubjectId: null
          })
        })
        // this.curriculumData = resp.data.list
      })
    },
    getClassList() {
      this.loading = true;
      findTeacherClassPageList({ pageNum: 1, pageSize: 100 }).then(response => {
        this.safeclassList = response.data.list;

      }
      );
    },
    getTermTimeList() {
      //查询学期
      listTermtime({ pageSize: 100, pageNum: 1, status: 1 }).then(response => {
        this.termTimeList = response.data.list;

      }
      );
    },
    /** 查询班级列表 */
    getList() {
      this.loading = true;
      findCurriculumPageList(this.queryParams).then(response => {
        this.bclassList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      }
      );
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        className: undefined,
        classTeacherId: undefined,
        status: "1",
        classDept: undefined,
        classSubject: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        className: undefined,
        status: undefined,
        classSubject: undefined,
        pageSize: 10,
        pageNum: 1
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班级信息";
      this.isUpdataOrAdd = 'add';
      this.getSessionsList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection)
      this.rowList = selection

      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true
      this.detailLoading = true
      this.isUpdataOrAdd = 'update'
      findDetail({ id: row.id }).then(resp => {
        this.form = resp.data
        this.curriculumData = resp.data.detailList
        this.detailLoading = false
      })
      this.classid = row.classId
      this.getSubjectListByClass()
    },

    /** 提交按钮 */
    submitForm: function () {
      const weekData = this.curriculumData
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.detailList = weekData
          addOrUpdateCurriculum(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            } else {
              this.msgError(response.message);
            }
          });

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return deleteCurriculum(row);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () { });
    },


  }
};
</script>

<style scoped lang="scss">
.curriculumTable {}

/deep/ .curriculumTable .cell {
  line-height: 26px;
  padding-left: 0px;
  padding-right: 0px;
}

/deep/ .curriculumTable .el-table__body td {
  padding: 0px 0px;
}
</style>